package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.ProFiLe;
import com.nikmesoft.android.referendumfriend.models.item_activities;
import com.nikmesoft.android.referendumfriend.models.userhobies;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.service.MyHobbiesHandler;
import com.nikmesoft.android.referendumfriend.service.ProfileHander;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class show_profile extends BaseActivity {
	EditText ed1, ed2, ed3, ed4, ed5;
	private ProgressDialog dialog;
	private WSLoader loader;
	String id = "";
	ProFiLe user;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showprofile);
		id = getIntent().getStringExtra("id").toString();
		init();
		update();
	}

	public void toad(String x) {
		CommonUtil.toastNotify(this, x);
	}

	public void init() {
		
		
		ed1 = (EditText) findViewById(R.id.show_fullname);
		ed2 = (EditText) findViewById(R.id.show_gender);
		ed3 = (EditText) findViewById(R.id.show_birthday);
		ed4 = (EditText) findViewById(R.id.show_phone);
		ed5 = (EditText) findViewById(R.id.show_email);

	}
	public void settext()
	{
		ed1.setText(user.getFullname());
		ed2.setText(user.getGender());
		ed3.setText(user.getBirthday());
		ed4.setText(user.getMobile());
		ed5.setText(user.getEmail());
	}
	public void update()
	{
		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(id);
		}
	}

	private String callWS(String id) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<getProfile soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<GetProfileRequest xsi:type=\"rdf:GetProfileRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:string\">"
				+ id
				+ "</id_user>"
				+ "</GetProfileRequest>"
				+ "</getProfile>"
				+ "</soapenv:Body>"
				+ "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private ProFiLe xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
		ProfileHander handler = new ProfileHander();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer,ProFiLe> {

		@Override
		protected ProFiLe doInBackground(String... params) {
			ProFiLe us = xmlParser(callWS(params[0]));
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(ProFiLe result) {
			super.onPostExecute(result);

		   user=result;
		   settext();
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

	public void callBack(View view) {
		finish();
	}
}
